package es.udc.pfc.davidparedes.web.pages.user;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;

import es.udc.pfc.davidparedes.model.storeservice.StoreService;
import es.udc.pfc.davidparedes.model.taskservice.TaskService;
import es.udc.pfc.davidparedes.model.universe.Universe;
import es.udc.pfc.davidparedes.model.userprofile.UserProfile;
import es.udc.pfc.davidparedes.model.userservice.UserService;
import es.udc.pfc.davidparedes.model.util.GlobalNames;
import es.udc.pfc.davidparedes.model.util.InstanceNotFoundException;
import es.udc.pfc.davidparedes.model.vendor.Vendor;

import es.udc.pfc.davidparedes.web.services.AuthenticationPolicy;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicyType;
import es.udc.pfc.davidparedes.web.util.UserSession;

@AuthenticationPolicy(AuthenticationPolicyType.MANAGER_OR_ABOVE)
public class AddTaskToVendor {
    
    @SessionState(create=false)
    private UserSession userSession;
    
    @Property
	private UserProfile userProfile;
    
    @Inject
    private UserService userService;
    
    @Inject
    private TaskService taskService;
    
    @Inject
    private StoreService storeService;

    @Property
    private Date startDate;
    
    @Property
    private Date endDate;
    
    @Property
    private String startTime;
    
    @Property
    private String endTime;
    
    @Property
    private Boolean isRange;
    
    @Property
    private Long vendorId;
    
    @Property
    private List<Universe> universes;
    
    @Property
    private Universe universe;
    
    @Property
    private String taskType;
    
    @Property
    private List<String> taskTypes;
    
    @Component
    private Form addTaskForm;
    
    @Inject 
    private PageRenderLinkSource pageLinkSource;
    
    @Inject
    private Messages messages;
    
    
    void onActivate(Long id) {
    	try {
    		Vendor vendor = userService.findVendor(id);
    		vendorId = id;
    		
    		userProfile = userService.findUserProfile(userSession.getUserProfileId());
    		universes = new ArrayList<Universe>();
    		universes.addAll(userProfile.getStore().getUniverses());
    		universe = vendor.getUniverse();
    		
    		taskTypes = new ArrayList<String>();
    		taskTypes.add(Character.toString(GlobalNames.TASK_NORMAL));
    		taskTypes.add(Character.toString(GlobalNames.TASK_VACATION));
    		taskTypes.add(Character.toString(GlobalNames.TASK_NIGHT));
    		taskTypes.add(Character.toString(GlobalNames.TASK_LOW));
    		taskTypes.add(Character.toString(GlobalNames.TASK_FESTIVE));
    		taskTypes.add(Character.toString(GlobalNames.TASK_ABSENTEEISM));
    		taskTypes.add(Character.toString(GlobalNames.TASK_COMPLEMENTARY_NORMAL));
    		taskTypes.add(Character.toString(GlobalNames.TASK_COMPLEMENTARY_FESTIVE));
    		taskTypes.add(Character.toString(GlobalNames.TASK_COMPLEMENTARY_NIGHT));
    		
			} catch (InstanceNotFoundException e) {
		}
    }

    Object onValidateFromAddTaskForm() {

        if (!addTaskForm.isValid()) {
            return this;
        }
        
        try {
			userService.findVendor(vendorId);
		} catch (InstanceNotFoundException e1) {
			addTaskForm.recordError(messages.get("error-notFound"));
		}
        
        String[] taskStartTime = startTime.split(":");
        Integer taskStartHour = Integer.parseInt(taskStartTime[0]);
        Integer taskStartMin = Integer.parseInt(taskStartTime[1]);
        Calendar taskStart = Calendar.getInstance();
        taskStart.setTime(startDate);
        if ((0 <= taskStartHour) && (taskStartHour <= 23) && (0 <= taskStartMin) && (taskStartMin <= 59)) {
	        taskStart.set(Calendar.HOUR_OF_DAY, taskStartHour);
	        taskStart.set(Calendar.MINUTE, taskStartMin);
        } else {
        	return this;
        }
        
        String[] taskEndTime = endTime.split(":");
        Integer taskEndHour = Integer.parseInt(taskEndTime[0]);
        Integer taskEndMin = Integer.parseInt(taskEndTime[1]);
        Calendar taskEnd = Calendar.getInstance();
        taskEnd.setTime(endDate);
        if ((0 <= taskEndHour) && (taskEndHour <= 23) && (0 <= taskEndMin) && (taskEndMin <= 59)) {
	        taskEnd.set(Calendar.HOUR_OF_DAY, taskEndHour);
	        taskEnd.set(Calendar.MINUTE, taskEndMin);
        } else {
        	return this;
        }
        
        if (taskStart.before(taskEnd)) {
        	try {
        		
        		if (isRange) {
        			taskService.addTasksRange(taskStart, taskEnd, (char) taskType.charAt(0), vendorId, universe.getUniverseId());
        		} else {
        			taskService.addTask(taskStart, taskEnd, (char) taskType.charAt(0), vendorId, universe.getUniverseId());
        		}
			} catch (InstanceNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        return pageLinkSource.createPageRenderLinkWithContext("user/DisplayVendorSchedule", vendorId);
        
    }
    
    public ValueEncoder<Universe> getUniverseEncoder() {

        return new ValueEncoder<Universe>() {

            @Override
            public String toClient(Universe value) {
                return String.valueOf(value.getUniverseId()); 
            }

            @Override
            public Universe toValue(String id) { 
            	
            	Universe universe = new Universe();
                try {
					universe = storeService.findUniverse(Long.parseLong(id));
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InstanceNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                
                return universe;
            }
        };
        
    }

}
